package org.budo.phone.ronglian;

import org.budo.phone.api.AbstractPhoneApi;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.java.security.util.DigestUtil;
import org.budo.time.Time;
import org.springframework.util.Base64Utils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class AbstractRonglianPhoneApi extends AbstractPhoneApi {
    private String restUrl = "https://sandboxapp.cloopen.com:8883";

    private String accountSid;

    private String accountToken;

    private String appId;

    /**
     * com.tj.plateform.util.call.YtxUtils.ivrCall(String, String, Long)
     * https://doc.yuntongxun.com/p/5a533a8f3b8496dd00dce019
     */
    // @Override
    public void dial(String phone) {
        dial_2(phone);
    }

    private void dial_2(String phone) {
        String str1 = this.getAccountSid() + this.getAccountToken() + Time.now().toString("yyyyMMddHHmmss");
        String sig = DigestUtil.md5(str1);

        String str2 = this.getAccountSid() + ":" + Time.now().toString("yyyyMMddHHmmss");
        String authorization = Base64Utils.encodeToString(str2.getBytes());

        String url = this.getRestUrl() + "/2013-12-26/Accounts/" + this.getAccountSid() + "/ivr/dial?sig=" + sig;

        Request request = new Request();
        request.setUrl(url);

        request.setHeader("Authorization", authorization);

        String requestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + "<Request>\r\n" + "  <Appid>" + this.getAppId() + "</Appid>\r\n" + "  <Dial number=\"" + phone + "\"></Dial>\r\n" + "</Request>";

        request.setRequestBody(requestBody);

        Response response = request.execute();

        log.info("#22 response=" + response);
    }
}